package com.thjk.bdf.system.service.controller;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.thjk.bdf.common.base.AjaxResult;
import com.thjk.bdf.common.enmus.ApplyEnum;
import com.thjk.bdf.common.enmus.UseEnum;
import com.thjk.bdf.common.entity.ApplyOrder;
import com.thjk.bdf.common.entity.BdfPayOut;
import com.thjk.bdf.system.http.request.BdOrderQueryRequest;
import com.thjk.bdf.system.http.response.vo.BdOrderData;
import com.thjk.bdf.system.http.response.vo.BdOrderQueryProduct;
import com.thjk.bdf.system.http.service.OrderService;
import com.thjk.bdf.system.service.dao.ApplyOrderMapper;
import com.thjk.bdf.system.service.dao.BdfPayOutMapper;

@RestController
@RequestMapping("/orderBatch")
public class OrderBatchController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(OrderBatchController.class);

	@Autowired
	private BdfPayOutMapper bdfPayOutMapper;
	
	@Autowired
	private ApplyOrderMapper applyOrderMapper;
	
	@Autowired
	private OrderService orderService;
	
	@GetMapping("/selectOrderInfos")
	public AjaxResult selectOrderInfos() {
		try {
			//先从数据库查询出要调用接口查询的订单号
			List<ApplyOrder> applyOrderList = applyOrderMapper.selectOrderInfos();
			//遍历要查询的订单号
			for (ApplyOrder applyOrder : applyOrderList) {
				//先获取token
				String token = orderService.getBdToken();
				if(StringUtils.isNotEmpty(token)) {
					//调用订单查询接口查询
					BdOrderQueryRequest bdOrderQueryRequest = new BdOrderQueryRequest();
					bdOrderQueryRequest.setToken(token);
					bdOrderQueryRequest.setApplicationNum(applyOrder.getSeriNo());
					BdOrderData bdOrderData = orderService.getBdOrderInfo(bdOrderQueryRequest);
					if(null != bdOrderData) {
						//更新授信申请表
						updateOrder(bdOrderData, applyOrder);
						//更新放款表
						BdOrderQueryProduct bdOrderQueryProducts[] = bdOrderData.getProducts();
						for (BdOrderQueryProduct bdOrderQueryProduct : bdOrderQueryProducts) {
							updatePayStatus(bdOrderQueryProduct, applyOrder);
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("error msg",e);
			return AjaxResult.error();
		}
		return AjaxResult.success();
	}
	/**
	 * 如果申请状态为04 审批通过，则不需要更新申请表
	 * @Description: 必要的描述
	 * @params:参宿说明
	 */
	private void updateOrder (BdOrderData bdOrderData,ApplyOrder applyOrder){
		String applyStatus = ApplyEnum.statusChange(bdOrderData.getApprovalStatus());
		if(StringUtils.isNotEmpty(applyStatus) && !applyStatus.equals(applyOrder.getStatus())) {
			ApplyOrder applyOrderUpdate = new ApplyOrder();
			applyOrderUpdate.setStatus(applyStatus);
			applyOrderUpdate.setRemark(bdOrderData.getApprovalStatusDesc());
			applyOrderUpdate.setCreditAmount(bdOrderData.getCreditAmount()==null?null:new BigDecimal(bdOrderData.getCreditAmount()));
			applyOrderUpdate.setScoreValidDate(bdOrderData.getScoreValidDate());
			applyOrderUpdate.setCanLoanAmount(null == bdOrderData.getCanLoanAmt() ? null : new BigDecimal(bdOrderData.getCanLoanAmt()));
			applyOrderUpdate.setBanDays(null == bdOrderData.getBanDays() ? null : bdOrderData.getBanDays().toString());
			applyOrderUpdate.setActivationLoanAmt(StringUtils.isEmpty(bdOrderData.getActivationLoanAmt()) ? null : new BigDecimal(bdOrderData.getActivationLoanAmt()));
			applyOrderUpdate.setActivationLoanTerm(bdOrderData.getActivationLoanTerm());
			applyOrderUpdate.setRejectReason(bdOrderData.getRejectReason());
			applyOrderUpdate.setSeriNo(applyOrder.getSeriNo());
			int a = applyOrderMapper.updateBySeriNoSelective(applyOrderUpdate);
			if(a==0){
				logger.error("----更新授信信息失败，数据异常----");
			}
		}
	}
	/**
	 * 
	 * @Description: 更新放款数据
	 * @params:参宿说明
	 */
	private void updatePayStatus(BdOrderQueryProduct bdOrderQueryProduct,ApplyOrder applyOrder){
		String useStatus = UseEnum.statusChange(bdOrderQueryProduct.getProductStatus());
		if(StringUtils.isNotEmpty(useStatus)) {
			BdfPayOut bdfPayOutUpdate = new BdfPayOut();
			bdfPayOutUpdate.setResult(useStatus);
			bdfPayOutUpdate.setProductId(bdOrderQueryProduct.getProductId());
			bdfPayOutUpdate.setPutoutNo(bdOrderQueryProduct.getPutoutNo());
			bdfPayOutUpdate.setFundingPartyName(bdOrderQueryProduct.getFundingPartyName());
			bdfPayOutUpdate.setProductStatus(bdOrderQueryProduct.getProductStatus());
			bdfPayOutUpdate.setProductStatusDesc(bdOrderQueryProduct.getProductStatusDesc());
			bdfPayOutUpdate.setPutoutAmt(null == bdOrderQueryProduct.getLoanAmt() ? null : new BigDecimal(bdOrderQueryProduct.getLoanAmt()));
			bdfPayOutUpdate.setPutoutDt(bdOrderQueryProduct.getLoanDate());
			bdfPayOutUpdate.setAnnualInterestRate(bdOrderQueryProduct.getAnnualInterestRate());
			bdfPayOutUpdate.setAPR(bdOrderQueryProduct.getAPR());
			int result = bdfPayOutMapper.updateByPutoutNoSelective(bdfPayOutUpdate);
			if(result == 0) {
				//更新失败，则进行插入
				bdfPayOutUpdate.setApplicationNum(applyOrder.getSeriNo());
				bdfPayOutMapper.insertSelective(bdfPayOutUpdate);
			}
		}
	}
}
